let currentUserPermissions = {};
let currentUserPermissionDetails = {};
let isSystemAdmin = false;
let permissionsLoaded = false; // 权限加载状态

//1. 修改权限加载函数，获取详细权限信息
//1. 修复权限加载函数
async function loadCurrentUserPermissions() {
    try {
        console.log('开始加载用户详细权限...');
        
        // 管理员直接给予所有权限
        if (currentUserType === 'ADMIN') {
            console.log('检测到管理员用户，授予完整系统权限');
            isSystemAdmin = true;
            setAdminPermissions();
            applyPermissionBasedUI();
            permissionsLoaded = true;
            return currentUserPermissions;
        }
        
        isSystemAdmin = false;
        
        const response = await fetch(`PermissionManagementServlet?action=getCurrentUserPermissionsDetailed&userId=${currentUserId}`);
        
        if (!response.ok) {
            throw new Error(`HTTP ${response.status}: ${response.statusText}`);
        }
        
        const data = await response.json();
        console.log('详细权限数据响应:', data);
        
        if (data.success) {
            currentUserPermissions = data.data?.permissions || data.permissions || {};
            currentUserPermissionDetails = data.data?.permissionDetails || data.permissionDetails || {};
            
            console.log('当前用户权限加载成功:', currentUserPermissions);
            
            permissionsLoaded = true;
            applyPermissionBasedUI();
            return currentUserPermissions;
        } else {
            throw new Error(data.message || '获取用户权限失败');
        }
    } catch (error) {
        console.error('加载用户权限失败:', error);
        currentUserPermissions = {};
        currentUserPermissionDetails = {};
        await loadDefaultPermissions();
        permissionsLoaded = true;
        throw error;
    }
}

// 3. 修复权限UI控制函数
//5. UI权限应用函数
function applyPermissionBasedUI() {
    console.log('应用权限基础UI设置...');
    
    const permissionUIMap = {
        'create_card': ['#addCardOne', '#addCardBatch', '#importCardBatch'],
        'edit_card': ['.edit-card'],
        'delete_card': ['.delete-card'],
        'create_folder': ['#addFolderBtn'],
        'delete_folder': ['.folder-delete'],
        'import_export': ['#importCardBatch', '#exportFile'],
        'search_replace': ['#searchBtn'],
        'print': ['#printBtn'],
        'manage_users': ['#accountsBtn'],
        'manage_permissions': ['#permissionsBtn']
    };
    
    Object.keys(permissionUIMap).forEach(permission => {
        const hasPermissionResult = isSystemAdmin || currentUserType === 'ADMIN' || currentUserPermissions[permission] === true;
        const selectors = permissionUIMap[permission];
        
        selectors.forEach(selector => {
            const elements = document.querySelectorAll(selector);
            elements.forEach(element => {
                if (hasPermissionResult) {
                    // 有权限：移除禁用状态
                    element.disabled = false;
                    element.classList.remove('permission-disabled');
                    element.style.opacity = '';
                    element.style.cursor = '';
                    element.style.filter = '';
                    removePermissionClickHandler(element);
                } else {
                    // 无权限：灰化
                    element.disabled = true;
                    element.classList.add('permission-disabled');
                    element.style.opacity = '0.5';
                    element.style.cursor = 'not-allowed';
                    element.style.filter = 'grayscale(70%)';
                    addPermissionClickHandler(element, permission);
                }
            });
        });
    });
    
    // 管理员功能按钮组特殊处理
    const adminButtons = document.querySelector('.admin-buttons');
    if (adminButtons) {
        if (isSystemAdmin || currentUserType === 'ADMIN') {
            adminButtons.style.opacity = '';
            adminButtons.style.filter = '';
            adminButtons.classList.remove('permission-disabled');
        } else {
            const hasAdminPermission = currentUserPermissions['manage_users'] || 
                                     currentUserPermissions['manage_permissions'];
            if (!hasAdminPermission) {
                adminButtons.style.opacity = '0.5';
                adminButtons.style.filter = 'grayscale(70%)';
                adminButtons.classList.add('permission-disabled');
            }
        }
    }
    
    console.log('权限UI设置完成');
}

//绑定用户操作事件
//5. 修复：增强的事件绑定函数
function bindUserActionEvents() {
    console.log('🔗 绑定用户操作事件...');
    
    // 防止重复绑定，先移除旧的事件监听器
    const resetButtons = document.querySelectorAll('.reset-password');
    const lockButtons = document.querySelectorAll('.lock-unlock-btn');
    const deleteButtons = document.querySelectorAll('.delete-user');
    
    // 重置密码按钮
    resetButtons.forEach(btn => {
        const newBtn = btn.cloneNode(true);
        btn.parentNode.replaceChild(newBtn, btn);
        
        newBtn.addEventListener('click', function(e) {
            e.preventDefault();
            const username = this.getAttribute('data-id');
            if (username && confirm('确定要重置用户 "' + username + '" 的密码吗？')) {
                resetUserPassword(username);
            }
        });
    });
    
    // 锁定/解锁按钮
    document.querySelectorAll('.lock-unlock-btn').forEach(btn => {
        const newBtn = btn.cloneNode(true);
        btn.parentNode.replaceChild(newBtn, btn);
        
        newBtn.addEventListener('click', function(e) {
            e.preventDefault();
            const username = this.getAttribute('data-id');
            const status = this.getAttribute('data-status');
            
            if (!username) return;
            
            if (status === 'ACTIVE') {
                if (confirm('确定要锁定用户 "' + username + '" 吗？')) {
                    lockUser(username);
                }
            } else {
                if (confirm('确定要解锁用户 "' + username + '" 吗？')) {
                    unlockUser(username);
                }
            }
        });
    });
    
    // 删除用户按钮
    document.querySelectorAll('.delete-user').forEach(btn => {
        const newBtn = btn.cloneNode(true);
        btn.parentNode.replaceChild(newBtn, btn);
        
        newBtn.addEventListener('click', function(e) {
            e.preventDefault();
            const userId = this.getAttribute('data-id');
            if (userId && confirm('确定要删除此用户吗？此操作不可撤销！')) {
                deleteUser(userId);
            }
        });
    });
    
    console.log('✅ 用户操作事件绑定完成');
}



//6. 紧急修复：在页面加载时立即应用修复
if (typeof window !== 'undefined' && window.addEventListener) {
 window.addEventListener('DOMContentLoaded', function() {
     console.log('🚨 应用用户数据提取修复补丁...');
     
     // 覆盖可能存在的问题函数
     if (typeof window.extractUserData === 'function') {
         console.log('🔧 覆盖全局extractUserData函数');
     }
     
     console.log('✅ 用户数据提取修复补丁应用完成');
 });
}

/**
 * 处理用户项点击事件
 */
function handleUserItemClick(event) {
    const userId = this.dataset.userId;
    const usernameEl = this.querySelector('.username');
    const username = usernameEl ? usernameEl.textContent : '';
    
    console.log('用户项被点击:', {userId, username});
    
    if (userId && username) {
        selectUserForPermission(parseInt(userId), username);
    } else {
        console.error('用户信息不完整:', {userId, username});
        showMessage('用户信息获取失败', 'error');
    }
}



//同时修复管理员权限设置函数
function setAdminPermissions() {
    currentUserPermissions = {
        'manage_users': true,
        'manage_permissions': true,
        'create_card': true,
        'edit_card': true,
        'delete_card': true,
        'create_folder': true,
        'delete_folder': true,
        'import_export': true,
        'search_replace': true,
        'print': true,
        'system_admin': true,
        // 确保管理员也有共享权限
        'share_cards': true,
        'share_folders': true, 
        'manage_shares': true
    };
    
    currentUserPermissionDetails = {};
    Object.keys(currentUserPermissions).forEach(perm => {
        currentUserPermissionDetails[perm] = {
            source: 'admin',
            granted: true,
            reason: '系统管理员拥有完整权限'
        };
    });
    
    console.log('管理员权限配置完成:', currentUserPermissions);
}


//3. 权限检查函数
function hasPermission(permissionName) {
    if (!permissionsLoaded) {
        console.warn('权限尚未加载完成:', permissionName);
        return false;
    }
    
    if (isSystemAdmin || currentUserType === 'ADMIN') {
        console.log(`管理员权限检查 ${permissionName}: true (管理员特权)`);
        return true;
    }
    
    const result = currentUserPermissions[permissionName] === true;
    console.log(`权限检查 ${permissionName}: ${result}`);
    return result;
}

// 4. 权限检查前置函数
function checkPermissionBeforeAction(permissionName, actionName) {
    if (isSystemAdmin || currentUserType === 'ADMIN') {
        console.log(`管理员执行操作: ${actionName} (跳过权限检查)`);
        return true;
    }
    
    if (!hasPermission(permissionName)) {
        showMessage(`您暂无"${actionName}"功能的使用权限，请联系管理员开启相关权限`, 'error');
        return false;
    }
    return true;
}


// 5. 修复用户权限变更处理函数
function handleUserPermissionChange(permissionId, granted) {
    if (!permissionData.currentSelectedUser) {
        showMessage('请先选择用户', 'error');
        return;
    }
    
    console.log('用户权限变更:', {
        userId: permissionData.currentSelectedUser,
        permissionId: permissionId,
        granted: granted
    });
    
    // 禁用相关控件防止重复操作
    const statusElements = document.querySelectorAll(`input[name="perm_${permissionId}"]`);
    statusElements.forEach(radio => radio.disabled = true);
    
    let actionUrl, formData = new FormData();
    formData.append('userId', permissionData.currentSelectedUser);
    formData.append('permissionId', permissionId);
    
    if (granted === null) {
        // 删除个人权限设置，使用默认（组权限）
        actionUrl = 'PermissionManagementServlet?action=removeUserPermission';
    } else {
        // 设置个人权限
        actionUrl = 'PermissionManagementServlet?action=setUserPermission';
        formData.append('granted', granted);
    }
    
    fetch(actionUrl, {
        method: 'POST',
        body: formData
    })
    .then(response => {
        if (!response.ok) {
            throw new Error(`HTTP ${response.status}: ${response.statusText}`);
        }
        return response.json();
    })
    .then(data => {
        statusElements.forEach(radio => radio.disabled = false);
        
        if (data.success) {
            showMessage('权限设置成功', 'success');
            // 重新加载用户权限以更新显示
            loadUserPermissions(permissionData.currentSelectedUser);
        } else {
            throw new Error(data.message || '权限设置失败');
        }
    })
    .catch(error => {
        statusElements.forEach(radio => radio.disabled = false);
        console.error('权限设置失败:', error);
        showMessage('权限设置失败: ' + error.message, 'error');
        
        // 恢复之前的选择状态
        loadUserPermissions(permissionData.currentSelectedUser);
    });
}

function enhanceUserTypeListeners() {
    document.querySelectorAll('input[name="userType"]').forEach(radio => {
        radio.addEventListener('change', function() {
            console.log('用户类型切换到:', this.value);
            loadUsersByType();
        });
    });
}

function initPermissionManagementEnhanced() {
    console.log('初始化增强版权限管理...');
    
    // 绑定用户类型切换事件
    enhanceUserTypeListeners();
    
    // 绑定标签页切换事件，确保数据正确加载
    initPermissionTabSwitching();
    
    // 加载初始数据
    Promise.all([
        loadAllPermissions(),
        loadUsersByGroup()
    ]).then(() => {
        console.log('权限管理初始化完成');
        
        // 默认选择第一个用户类型并加载用户
        const firstUserTypeRadio = document.querySelector('input[name="userType"]');
        if (firstUserTypeRadio) {
            firstUserTypeRadio.checked = true;
            loadUsersByType();
        }
    }).catch(error => {
        console.error('权限管理初始化失败:', error);
        showMessage('权限管理初始化失败: ' + error.message, 'error');
    });
}

//应用修复的主函数
function applyPermissionFixes() {
    console.log('应用权限管理修复...');
    
    // 重新初始化权限管理
    setTimeout(() => {
        initPermissionManagementEnhanced();
    }, 100);
    
    console.log('权限管理修复已应用');
}

//4. 获取权限拒绝原因
function getPermissionDenialReason(permissionName) {
    const permissionDetail = currentUserPermissionDetails[permissionName];
    
    if (!permissionDetail) {
        return {
            reason: 'not_configured',
            message: '该功能权限未配置'
        };
    }
    
    // 根据权限来源和状态判断拒绝原因
    switch (permissionDetail.source) {
        case 'personal':
            return {
                reason: 'personal_denied',
                message: '您的个人权限设置拒绝了此功能'
            };
        case 'group':
            return {
                reason: 'group_denied', 
                message: '您所在的用户组无此功能权限'
            };
        case 'default':
            return {
                reason: 'default_denied',
                message: '系统默认禁用了此功能'
            };
        default:
            return {
                reason: 'unknown',
                message: '权限状态未知'
            };
    }
}

function checkPermissionBeforeAction(permissionName, actionName) {
    if (hasPermission(permissionName)) {
        return true;
    }
    
    // 获取详细的拒绝原因
    const denialInfo = getPermissionDenialReason(permissionName);
    
    let detailedMessage;
    switch (denialInfo.reason) {
        case 'personal_denied':
            detailedMessage = `您暂无"${actionName}"功能的使用权限。\n\n原因：${denialInfo.message}\n建议：请联系管理员为您开启个人权限设置。`;
            break;
        case 'group_denied':
            detailedMessage = `您暂无"${actionName}"功能的使用权限。\n\n原因：${denialInfo.message}\n建议：请联系管理员为您的用户组开启此权限。`;
            break;
        case 'default_denied':
            detailedMessage = `您暂无"${actionName}"功能的使用权限。\n\n原因：${denialInfo.message}\n建议：请联系系统管理员。`;
            break;
        default:
            detailedMessage = `您暂无"${actionName}"功能的使用权限。\n\n${denialInfo.message}`;
    }
    
    showMessage(detailedMessage, 'error');
    return false;
}

//3. 修改UI应用函数，改为灰化而不是隐藏
function applyPermissionBasedUI() {
    console.log('应用权限基础UI设置（灰化模式）...');
    
    // 权限到UI元素的映射
    const permissionUIMap = {
        'create_card': [
            '#addCardOne', 
            '#addCardBatch', 
            '#importCardBatch',
            '.new-card-btn'
        ],
        'edit_card': [
            '.edit-card'
        ],
        'delete_card': [
            '.delete-card'
        ],
        'create_folder': [
            '#addFolderBtn'
        ],
        'delete_folder': [
            '.folder-delete'
        ],
        'import_export': [
            '#importCardBatch', 
            '#exportFile'
        ],
        'search_replace': [
            '#searchBtn'
        ],
        'print': [
            '#printBtn'
        ],
        'manage_users': [
            '#accountsBtn'
        ],
        'manage_permissions': [
            '#permissionsBtn'
        ]
    };
    
    // 遍历权限映射，设置UI状态
    Object.keys(permissionUIMap).forEach(permission => {
        const hasPermission = currentUserPermissions[permission] === true;
        const selectors = permissionUIMap[permission];
        
        selectors.forEach(selector => {
            // 使用延迟查找，因为某些元素可能还没有加载
            setTimeout(() => {
                const elements = document.querySelectorAll(selector);
                elements.forEach(element => {
                    if (hasPermission) {
                        // 有权限：移除禁用状态
                        element.disabled = false;
                        element.classList.remove('permission-disabled');
                        element.style.opacity = '';
                        element.style.cursor = '';
                        element.style.filter = '';
                        
                        // 移除权限检查事件监听器
                        removePermissionClickHandler(element);
                    } else {
                        // 无权限：灰化但不隐藏
                        element.disabled = true;
                        element.classList.add('permission-disabled');
                        element.style.opacity = '0.5';
                        element.style.cursor = 'not-allowed';
                        element.style.filter = 'grayscale(70%)';
                        
                        // 添加权限检查事件监听器
                        addPermissionClickHandler(element, permission);
                    }
                });
            }, 100);
        });
    });
    
    // 特殊处理：管理员功能按钮组（灰化而不是隐藏）
    setTimeout(() => {
        const adminButtons = document.querySelector('.admin-buttons');
        if (adminButtons) {
            const hasAdminPermission = currentUserPermissions['manage_users'] || 
                                     currentUserPermissions['manage_permissions'];
            if (!hasAdminPermission) {
                adminButtons.style.opacity = '0.5';
                adminButtons.style.filter = 'grayscale(70%)';
            }
        }
    }, 100);
    
    console.log('权限UI设置完成（灰化模式）');
}

//6. 添加权限检查点击处理器（仅对普通用户）
function addPermissionClickHandler(element, permissionName) {
    // 管理员不需要权限检查处理器
    if (isSystemAdmin || currentUserType === 'ADMIN') {
        return;
    }
    
    // 先移除可能存在的旧处理器
    removePermissionClickHandler(element);
    
    // 创建新的点击处理器
    const clickHandler = function(e) {
        e.preventDefault();
        e.stopPropagation();
        
        // 获取功能名称
        const actionName = getActionNameByPermission(permissionName);
        
        // 执行权限检查并显示详细提示
        checkPermissionBeforeAction(permissionName, actionName);
        
        return false;
    };
    
    // 保存处理器引用并绑定事件
    element._permissionClickHandler = clickHandler;
    element.addEventListener('click', clickHandler, true); // 使用捕获阶段，确保优先执行
}

// 7. 移除权限检查点击处理器
function removePermissionClickHandler(element) {
    if (element._permissionClickHandler) {
        element.removeEventListener('click', element._permissionClickHandler, true);
        delete element._permissionClickHandler;
    }
}

//8. 权限名称到功能名称的映射
function getActionNameByPermission(permissionName) {
    const actionNameMap = {
        'create_card': '创建名片',
        'edit_card': '编辑名片',
        'delete_card': '删除名片',
        'create_folder': '创建名片夹',
        'delete_folder': '删除名片夹',
        'import_export': '导入导出',
        'search_replace': '查找替换',
        'print': '打印',
        'manage_users': '用户管理',
        'manage_permissions': '权限管理'
    };
    
    return actionNameMap[permissionName] || '未知功能';
}

//7. 增强默认权限加载
//修复默认权限加载函数 - 添加共享相关权限
async function loadDefaultPermissions() {
    try {
        // 如果是管理员，给予完整权限
        if (currentUserType === 'ADMIN') {
            setAdminPermissions();
        } else {
            // 普通用户的基本权限 - 添加共享相关权限
            currentUserPermissions = {
                'create_card': true,
                'edit_card': true,
                'delete_card': true,
                'create_folder': true,
                'import_export': true,
                'search_replace': true,
                'print': true,
                // 新增：共享相关权限
                'share_cards': true,      // 共享名片权限
                'share_folders': true,    // 共享名片夹权限  
                'manage_shares': true     // 管理共享权限（查看我的共享、撤销共享等）
            };
            
            // 设置普通用户权限详情
            currentUserPermissionDetails = {};
            Object.keys(currentUserPermissions).forEach(perm => {
                currentUserPermissionDetails[perm] = {
                    source: 'default',
                    granted: true,
                    reason: '普通用户默认权限'
                };
            });
            
            // 无权限的功能
            ['manage_users', 'manage_permissions'].forEach(perm => {
                currentUserPermissions[perm] = false;
                currentUserPermissionDetails[perm] = {
                    source: 'default',
                    granted: false,
                    reason: '需要管理员权限'
                };
            });
        }
        
        console.log('使用默认权限配置:', currentUserPermissions);
        console.log('默认权限详情:', currentUserPermissionDetails);
        applyPermissionBasedUI();
    } catch (error) {
        console.error('加载默认权限失败:', error);
    }
}

//8. 权限刷新函数
function refreshPermissionsAndUI() {
    console.log('刷新权限和UI状态...');
    return loadCurrentUserPermissions().then(() => {
        console.log('权限刷新完成');
        // 重新应用UI状态
        applyPermissionBasedUI();
    }).catch(error => {
        console.error('权限刷新失败:', error);
    });
}

//9. 权限状态检查函数（用于调试）
function debugPermissionStatus(permissionName) {
    console.group(`权限状态检查: ${permissionName}`);
    console.log('用户类型:', currentUserType);
    console.log('是否系统管理员:', isSystemAdmin);
    console.log('基础权限:', currentUserPermissions[permissionName]);
    console.log('详细信息:', currentUserPermissionDetails[permissionName]);
    
    if (!hasPermission(permissionName)) {
        const denialInfo = getPermissionDenialReason(permissionName);
        console.log('拒绝原因:', denialInfo);
    }
    console.groupEnd();
}

function isAdminUser() {
    return isSystemAdmin || currentUserType === 'ADMIN';
}

// 14. 安全权限检查函数（用于敏感操作）
function checkAdminPermission(actionName) {
    if (!isAdminUser()) {
        showMessage(`抱歉，"${actionName}"需要管理员权限`, 'error');
        return false;
    }
    return true;
}

//15. 用户权限变更处理函数
function handleUserPermissionChange(permissionId, granted) {
    if (!permissionData.currentSelectedUser) {
        showMessage('请先选择用户', 'error');
        return;
    }
    
    console.log('用户权限变更:', {
        userId: permissionData.currentSelectedUser,
        permissionId: permissionId,
        granted: granted
    });
    
    // 禁用相关控件防止重复操作
    const statusElements = document.querySelectorAll(`input[name="perm_${permissionId}"]`);
    statusElements.forEach(radio => radio.disabled = true);
    
    let actionUrl, formData = new FormData();
    formData.append('userId', permissionData.currentSelectedUser);
    formData.append('permissionId', permissionId);
    
    if (granted === null) {
        // 删除个人权限设置，使用默认（组权限）
        actionUrl = 'PermissionManagementServlet?action=removeUserPermission';
    } else {
        // 设置个人权限
        actionUrl = 'PermissionManagementServlet?action=setUserPermission';
        formData.append('granted', granted);
    }
    
    fetch(actionUrl, {
        method: 'POST',
        body: formData
    })
    .then(response => {
        if (!response.ok) {
            throw new Error(`HTTP ${response.status}: ${response.statusText}`);
        }
        return response.json();
    })
    .then(data => {
        statusElements.forEach(radio => radio.disabled = false);
        
        if (data.success) {
            showMessage('权限设置成功', 'success');
            // 重新加载用户权限以更新显示
            loadUserPermissions(permissionData.currentSelectedUser);
        } else {
            throw new Error(data.message || '权限设置失败');
        }
    })
    .catch(error => {
        statusElements.forEach(radio => radio.disabled = false);
        console.error('权限设置失败:', error);
        showMessage('权限设置失败: ' + error.message, 'error');
        
        // 恢复之前的选择状态
        loadUserPermissions(permissionData.currentSelectedUser);
    });
}

//16. 权限管理功能初始化
function initPermissionManagement() {
    console.log('初始化权限管理...');
    
    // 添加加载状态
    setPermissionLoadingState(true);
    
    // 绑定事件
    bindPermissionEvents();
    
    // 加载数据
    Promise.all([
        loadAllPermissions(),
        loadUsersByGroup()
    ]).then(() => {
        console.log('权限管理初始化完成');
        setPermissionLoadingState(false);
    }).catch(error => {
        console.error('权限管理初始化失败:', error);
        showMessage('权限管理初始化失败: ' + error.message, 'error');
        setPermissionLoadingState(false);
    });
}

//17. 设置加载状态
function setPermissionLoadingState(loading) {
    if (typeof permissionData !== 'undefined') {
        permissionData.isLoading = loading;
    }
    
    // 更新UI状态
    const loadingElements = document.querySelectorAll('.loading-placeholder');
    loadingElements.forEach(el => {
        if (loading) {
            el.innerHTML = '<i class="fas fa-spinner fa-spin"></i><span>加载中...</span>';
        }
    });
}

// 18. 绑定权限管理事件
function bindPermissionEvents() {
    // 刷新按钮
    const refreshBtn = document.getElementById('refreshUserGroups');
    if (refreshBtn) {
        refreshBtn.addEventListener('click', () => {
            refreshBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> 刷新中...';
            loadUsersByGroup().finally(() => {
                refreshBtn.innerHTML = '<i class="fas fa-sync-alt"></i> 刷新数据';
            });
        });
    }
    
    // 用户类型切换
    document.querySelectorAll('input[name="userType"]').forEach(radio => {
        radio.addEventListener('change', loadUsersByType);
    });
    
    // 用户搜索
    const searchInput = document.getElementById('userSearchInput');
    if (searchInput) {
        searchInput.addEventListener('input', debounce(filterUsers, 300));
    }
    
    // 重置和保存按钮
    const resetBtn = document.getElementById('resetDefaultPermissions');
    const saveBtn = document.getElementById('saveUserPermissions');
    const previewBtn = document.getElementById('previewPermissions');
    
    if (resetBtn) {
        resetBtn.addEventListener('click', resetUserPermissions);
    }
    if (saveBtn) {
        saveBtn.addEventListener('click', saveUserPermissions);
    }
    if (previewBtn) {
        previewBtn.addEventListener('click', previewUserPermissions);
    }
}

//11. 初始化增强权限系统
function initEnhancedPermissionSystem() {
    console.log('初始化增强权限系统（管理员特权版）...');
    console.log('当前用户类型:', currentUserType);
    
    // 检查用户类型并设置管理员标识
    if (currentUserType === 'ADMIN') {
        isSystemAdmin = true;
        console.log('检测到管理员用户');
    }
    
    // 加载权限
    return loadCurrentUserPermissions().catch(error => {
        console.error('权限系统初始化失败:', error);
        showMessage('权限系统初始化失败，将使用默认权限', 'error');
        return loadDefaultPermissions();
    });
}
//导出函数供外部使用
window.enhancedPermissionManager = {
    init: initEnhancedPermissionSystem,
    checkPermission: checkPermissionBeforeAction,
    hasPermission: hasPermission,
    refresh: applyPermissionBasedUI,
    isLoaded: () => permissionsLoaded
};

//权限管理专用标签页切换函数
function initPermissionTabSwitching() {
    console.log('初始化权限管理标签页切换...');
    
    // 权限管理专用标签页切换
    document.querySelectorAll('.permission-tab').forEach(tab => {
        tab.addEventListener('click', function() {
            const targetTab = this.dataset.permissionTab;
            console.log('切换到权限标签页:', targetTab);
            
            // 移除所有活动状态
            document.querySelectorAll('.permission-tab').forEach(t => {
                t.classList.remove('active');
            });
            document.querySelectorAll('.permission-tab-content').forEach(content => {
                content.classList.remove('active');
            });
            
            // 激活当前标签
            this.classList.add('active');
            const targetContent = document.getElementById(targetTab + 'Content');
            if (targetContent) {
                targetContent.classList.add('active');
                console.log('已激活标签页内容:', targetTab + 'Content');
            } else {
                console.error('找不到标签页内容容器:', targetTab + 'Content');
            }
            
            // 根据标签页加载相应数据
            setTimeout(() => {
                switch (targetTab) {
                    case 'userGroups':
                        loadUsersByGroup();
                        break;
                    case 'groupPermissions':
                        renderGroupPermissions();
                        break;
                    case 'userPermissions':
                        loadUsersByType();
                        break;
                }
            }, 100);
        });
    });
}

// 权限管理功能初始化
function initPermissionManagement() {
    console.log('初始化权限管理...');
    
    // 添加加载状态
    setPermissionLoadingState(true);
    
    // 绑定事件
    bindPermissionEvents();
    
    // 加载数据
    Promise.all([
        loadAllPermissions(),
        loadUsersByGroup()
    ]).then(() => {
        console.log('权限管理初始化完成');
        setPermissionLoadingState(false);
    }).catch(error => {
        console.error('权限管理初始化失败:', error);
        showMessage('权限管理初始化失败: ' + error.message, 'error');
        setPermissionLoadingState(false);
    });
}

// 设置加载状态
function setPermissionLoadingState(loading) {
    permissionData.isLoading = loading;
    
    // 更新UI状态
    const loadingElements = document.querySelectorAll('.loading-placeholder');
    loadingElements.forEach(el => {
        if (loading) {
            el.innerHTML = '<i class="fas fa-spinner fa-spin"></i><span>加载中...</span>';
        }
    });
}

// 绑定权限管理事件
function bindPermissionEvents() {
    // 刷新按钮
    const refreshBtn = document.getElementById('refreshUserGroups');
    if (refreshBtn) {
        refreshBtn.addEventListener('click', () => {
            refreshBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> 刷新中...';
            loadUsersByGroup().finally(() => {
                refreshBtn.innerHTML = '<i class="fas fa-sync-alt"></i> 刷新数据';
            });
        });
    }
    
    // 用户类型切换
    document.querySelectorAll('input[name="userType"]').forEach(radio => {
        radio.addEventListener('change', loadUsersByType);
    });
    
    // 用户搜索
    const searchInput = document.getElementById('userSearchInput');
    if (searchInput) {
        searchInput.addEventListener('input', debounce(filterUsers, 300));
    }
    
    // 重置和保存按钮
    const resetBtn = document.getElementById('resetDefaultPermissions');
    const saveBtn = document.getElementById('saveUserPermissions');
    const previewBtn = document.getElementById('previewPermissions');
    
    if (resetBtn) {
        resetBtn.addEventListener('click', resetUserPermissions);
    }
    if (saveBtn) {
        saveBtn.addEventListener('click', saveUserPermissions);
    }
    if (previewBtn) {
        previewBtn.addEventListener('click', previewUserPermissions);
    }
    
    // 标签页切换事件
    const userGroupsTab = document.querySelector('[data-tab="userGroups"]');
    const groupPermissionsTab = document.querySelector('[data-tab="groupPermissions"]');
    const userPermissionsTab = document.querySelector('[data-tab="userPermissions"]');
    
    if (userGroupsTab) {
        userGroupsTab.addEventListener('click', () => {
            setTimeout(loadUsersByGroup, 100);
        });
    }
    
    if (groupPermissionsTab) {
        groupPermissionsTab.addEventListener('click', () => {
            setTimeout(renderGroupPermissions, 100);
        });
    }
    
    if (userPermissionsTab) {
        userPermissionsTab.addEventListener('click', () => {
            setTimeout(loadUsersByType, 100);
        });
    }
}

// 防抖函数
function debounce(func, wait) {
    let timeout;
    return function executedFunction(...args) {
        const later = () => {
            clearTimeout(timeout);
            func(...args);
        };
        clearTimeout(timeout);
        timeout = setTimeout(later, wait);
    };
}

// 加载所有权限
function loadAllPermissions() {
    return fetch('PermissionManagementServlet?action=getAllPermissions')
        .then(response => {
            if (!response.ok) {
                throw new Error('HTTP ' + response.status + ': ' + response.statusText);
            }
            return response.json();
        })
        .then(data => {
            console.log('权限数据响应:', data);
            if (data.success) {
                permissionData.allPermissions = data.permissions || [];
                console.log('成功加载权限:', permissionData.allPermissions.length, '个');
                return data.permissions;
            } else {
                throw new Error(data.message || '获取权限失败');
            }
        })
        .catch(error => {
            console.error('加载权限失败:', error);
            showMessage('加载权限失败: ' + error.message, 'error');
            throw error;
        });
}

// 加载用户分组
function loadUsersByGroup() {
    return fetch('PermissionManagementServlet?action=getUsersByGroup')
        .then(response => {
            if (!response.ok) {
                throw new Error('HTTP ' + response.status + ': ' + response.statusText);
            }
            return response.json();
        })
        .then(data => {
            console.log('用户分组数据:', data);
            if (data.success) {
                renderUserGroups(data.adminUsers || [], data.normalUsers || []);
                initDragAndDrop();
                updateUserCounts(data.adminUsers ? data.adminUsers.length : 0, data.normalUsers ? data.normalUsers.length : 0);
                return data;
            } else {
                throw new Error(data.message || '获取用户分组失败');
            }
        })
        .catch(error => {
            console.error('加载用户分组失败:', error);
            showMessage('加载用户分组失败: ' + error.message, 'error');
            
            // 显示错误状态
            displayErrorState('#adminUserList', '加载管理员失败');
            displayErrorState('#normalUserList', '加载用户失败');
            throw error;
        });
}

// 更新用户计数
//更新用户组计数
function updateUserCounts() {
    const adminCount = document.getElementById('adminUserList').children.length;
    const userCount = document.getElementById('normalUserList').children.length;
    
    const adminCountEl = document.getElementById('adminCount');
    const userCountEl = document.getElementById('userCount');
    
    if (adminCountEl) adminCountEl.textContent = adminCount;
    if (userCountEl) userCountEl.textContent = userCount;
}

// 渲染用户分组
function renderUserGroups(adminUsers, normalUsers) {
    const adminList = document.getElementById('adminUserList');
    const normalList = document.getElementById('normalUserList');
    
    if (!adminList || !normalList) {
        console.error('找不到用户列表元素');
        return;
    }
    
    // 渲染管理员用户
    if (adminUsers && adminUsers.length > 0) {
        var adminHtml = '';
        for (var i = 0; i < adminUsers.length; i++) {
            var user = adminUsers[i];
            var delay = (i * 0.1) + 's';
            adminHtml += '<div class="user-item" draggable="true" ' +
                        'data-user-id="' + user.userId + '" ' +
                        'data-current-group="admin" ' +
                        'style="animation-delay: ' + delay + '">' +
                        '<i class="fas fa-crown"></i>' +
                        '<div class="user-info">' +
                        '<div class="username">' + (user.username || '') + '</div>' +
                        '<div class="email">' + (user.email || '') + '</div>' +
                        '</div>' +
                        '<i class="fas fa-grip-vertical" style="color: #ccc;"></i>' +
                        '</div>';
        }
        adminList.innerHTML = adminHtml;
    } else {
        adminList.innerHTML = '<div class="empty-hint">暂无管理员用户<br><small>拖拽用户到此区域提升为管理员</small></div>';
    }
    
    // 渲染普通用户
    if (normalUsers && normalUsers.length > 0) {
        var normalHtml = '';
        for (var i = 0; i < normalUsers.length; i++) {
            var user = normalUsers[i];
            var delay = (i * 0.1) + 's';
            normalHtml += '<div class="user-item" draggable="true" ' +
                         'data-user-id="' + user.userId + '" ' +
                         'data-current-group="user" ' +
                         'style="animation-delay: ' + delay + '">' +
                         '<i class="fas fa-user"></i>' +
                         '<div class="user-info">' +
                         '<div class="username">' + (user.username || '') + '</div>' +
                         '<div class="email">' + (user.email || '') + '</div>' +
                         '</div>' +
                         '<i class="fas fa-grip-vertical" style="color: #ccc;"></i>' +
                         '</div>';
        }
        normalList.innerHTML = normalHtml;
    } else {
        normalList.innerHTML = '<div class="empty-hint">暂无普通用户<br><small>拖拽用户到此区域设为普通用户</small></div>';
    }
}

// 显示错误状态
function displayErrorState(selector, message) {
    const element = document.querySelector(selector);
    if (element) {
        element.innerHTML = '<div class="error-state">' +
            '<i class="fas fa-exclamation-triangle" style="color: #e74c3c; font-size: 24px;"></i>' +
            '<p style="color: #e74c3c; margin: 10px 0;">' + message + '</p>' +
            '<button class="btn btn-secondary btn-sm" onclick="loadUsersByGroup()">' +
            '<i class="fas fa-redo"></i> 重试' +
            '</button>' +
            '</div>';
    }
}

// 初始化拖拽功能
function initDragAndDrop() {
    const userItems = document.querySelectorAll('.user-item[draggable="true"]');
    const userLists = document.querySelectorAll('.user-list');
    
    console.log('初始化拖拽，用户项数量:', userItems.length, '目标区域数量:', userLists.length);
    
    userItems.forEach(item => {
        // 移除旧的事件监听器
        item.removeEventListener('dragstart', handleDragStart);
        item.removeEventListener('dragend', handleDragEnd);
        
        // 添加新的事件监听器
        item.addEventListener('dragstart', handleDragStart);
        item.addEventListener('dragend', handleDragEnd);
        
        // 添加鼠标悬停效果
        item.addEventListener('mouseenter', function() {
            this.style.transform = 'translateY(-2px)';
        });
        
        item.addEventListener('mouseleave', function() {
            if (!this.classList.contains('dragging')) {
                this.style.transform = '';
            }
        });
    });
    
    userLists.forEach(list => {
        // 移除旧的事件监听器
        list.removeEventListener('dragover', handleDragOver);
        list.removeEventListener('drop', handleDrop);
        list.removeEventListener('dragenter', handleDragEnter);
        list.removeEventListener('dragleave', handleDragLeave);
        
        // 添加新的事件监听器
        list.addEventListener('dragover', handleDragOver);
        list.addEventListener('drop', handleDrop);
        list.addEventListener('dragenter', handleDragEnter);
        list.addEventListener('dragleave', handleDragLeave);
    });
}

// 拖拽开始
function handleDragStart(e) {
    console.log('开始拖拽:', this.dataset.userId);
    this.classList.add('dragging');
    
    // 设置拖拽数据
    e.dataTransfer.setData('text/plain', this.dataset.userId);
    e.dataTransfer.setData('current-group', this.dataset.currentGroup);
    e.dataTransfer.setData('username', this.querySelector('.username').textContent);
    
    // 设置拖拽效果
    e.dataTransfer.effectAllowed = 'move';
    
    // 添加拖拽样式
    setTimeout(() => {
        this.style.opacity = '0.5';
    }, 0);
}

// 拖拽结束
function handleDragEnd(e) {
    console.log('拖拽结束');
    this.classList.remove('dragging');
    this.style.opacity = '';
    this.style.transform = '';
    
    // 移除所有目标区域的拖拽状态
    document.querySelectorAll('.user-list').forEach(list => {
        list.classList.remove('drag-over');
    });
}

// 拖拽经过
function handleDragOver(e) {
    e.preventDefault();
    e.dataTransfer.dropEffect = 'move';
}

// 拖拽进入
function handleDragEnter(e) {
    e.preventDefault();
    if (this.classList.contains('user-list')) {
        this.classList.add('drag-over');
        console.log('拖拽进入目标区域:', this.dataset.group);
    }
}

// 拖拽离开
function handleDragLeave(e) {
    // 检查是否真的离开了目标区域
    if (!this.contains(e.relatedTarget)) {
        this.classList.remove('drag-over');
        console.log('拖拽离开目标区域');
    }
}

// 拖拽放下
function handleDrop(e) {
    e.preventDefault();
    this.classList.remove('drag-over');
    
    const userId = e.dataTransfer.getData('text/plain');
    const currentGroup = e.dataTransfer.getData('current-group');
    const username = e.dataTransfer.getData('username');
    const targetGroup = this.dataset.group;
    
    console.log('拖拽放下:', {userId, currentGroup, targetGroup, username});
    
    if (currentGroup !== targetGroup) {
        // 显示确认对话框
        const groupName = targetGroup === 'admin' ? '管理员组' : '普通用户组';
        if (confirm('确定要将用户"' + username + '"移动到' + groupName + '吗？')) {
            moveUserToGroup(userId, targetGroup);
        }
    } else {
        showMessage('用户已在目标组中', 'info');
    }
}

// 移动用户到指定组
function moveUserToGroup(userId, targetGroup) {
    const formData = new FormData();
    formData.append('userId', userId);
    formData.append('targetGroup', targetGroup);
    
    
    // 显示加载状态
    showLoader();
    
    fetch('PermissionManagementServlet?action=moveUserToGroup', {
        method: 'POST',
        body: formData
    })
    .then(response => {
        if (!response.ok) {
            throw new Error('HTTP ' + response.status + ': ' + response.statusText);
        }
        return response.json();
    })
    .then(data => {
        hideLoader();
        if (data.success) {
            showMessage(data.message, 'success');
            // 重新加载用户分组
            loadUsersByGroup();
        } else {
            throw new Error(data.message || '移动用户失败');
        }
    })
    .catch(error => {
        hideLoader();
        console.error('移动用户失败:', error);
        showMessage('移动用户失败: ' + error.message, 'error');
    });
}

// 渲染组权限
function renderGroupPermissions() {
    console.log('渲染组权限...');
    
    const adminContainer = document.getElementById('adminGroupPermissions');
    const userContainer = document.getElementById('userGroupPermissions');
    
    if (!adminContainer || !userContainer) {
        console.error('找不到权限容器元素');
        return;
    }
    
    // 显示加载状态
    adminContainer.innerHTML = '<div class="loading-placeholder"><i class="fas fa-spinner fa-spin"></i><span>加载权限中...</span></div>';
    userContainer.innerHTML = '<div class="loading-placeholder"><i class="fas fa-spinner fa-spin"></i><span>加载权限中...</span></div>';
    
    // 加载管理员组权限
    Promise.all([
        fetch('PermissionManagementServlet?action=getGroupPermissions&groupType=admin'),
        fetch('PermissionManagementServlet?action=getGroupPermissions&groupType=user')
    ]).then(responses => {
        return Promise.all(responses.map(r => {
            if (!r.ok) {
                throw new Error('HTTP ' + r.status + ': ' + r.statusText);
            }
            return r.json();
        }));
    }).then(results => {
        var adminData = results[0];
        var userData = results[1];
        
        console.log('组权限数据:', {adminData, userData});
        
        if (adminData.success && userData.success) {
            renderPermissionGrid(adminContainer, adminData.allPermissions, adminData.groupPermissionIds, 'admin');
            renderPermissionGrid(userContainer, userData.allPermissions, userData.groupPermissionIds, 'user');
            
            // 更新统计
            updatePermissionStats('admin', adminData.allPermissions.length, adminData.groupPermissionIds.length);
            updatePermissionStats('user', userData.allPermissions.length, userData.groupPermissionIds.length);
        } else {
            throw new Error('获取组权限失败');
        }
    }).catch(error => {
        console.error('渲染组权限失败:', error);
        adminContainer.innerHTML = '<div class="error-state"><i class="fas fa-exclamation-triangle"></i><p>加载失败: ' + error.message + '</p></div>';
        userContainer.innerHTML = '<div class="error-state"><i class="fas fa-exclamation-triangle"></i><p>加载失败: ' + error.message + '</p></div>';
        showMessage('加载组权限失败: ' + error.message, 'error');
    });
}

// 更新权限统计
function updatePermissionStats(groupType, totalCount, grantedCount) {
    const grantedEl = document.getElementById(groupType + 'GrantedCount');
    const totalEl = document.getElementById(groupType + 'TotalCount');
    
    if (grantedEl) grantedEl.textContent = grantedCount;
    if (totalEl) totalEl.textContent = totalCount;
}

// 渲染权限网格
function renderPermissionGrid(container, permissions, grantedIds, groupType) {
    if (!permissions || permissions.length === 0) {
        container.innerHTML = '<div class="empty-hint">暂无权限数据</div>';
        return;
    }
    
    var html = '';
    for (var i = 0; i < permissions.length; i++) {
        var permission = permissions[i];
        var isGranted = grantedIds.indexOf(permission.permissionId) !== -1;
        var delay = (i * 0.05) + 's';
        
        html += '<div class="permission-item" style="animation-delay: ' + delay + '">' +
                '<span class="permission-name">' + (permission.permissionDescription || permission.permissionName) + '</span>' +
                '<div class="permission-toggle">' +
                '<input type="checkbox" class="permission-checkbox" ' +
                'data-permission-id="' + permission.permissionId + '" ' +
                'data-group-type="' + groupType + '" ' +
                (isGranted ? 'checked' : '') + '>' +
                '<span class="permission-status ' + (isGranted ? 'granted' : 'denied') + '">' +
                (isGranted ? '已授权' : '未授权') +
                '</span>' +
                '</div>' +
                '</div>';
    }
    
    container.innerHTML = html;
    
    // 绑定权限切换事件
    container.querySelectorAll('.permission-checkbox').forEach(checkbox => {
        checkbox.addEventListener('change', handleGroupPermissionChange);
    });
}

// 处理组权限变更
function handleGroupPermissionChange(e) {
    const permissionId = e.target.dataset.permissionId;
    const groupType = e.target.dataset.groupType;
    const granted = e.target.checked;
    const groupId = groupType === 'admin' ? 1 : 2;
    
    console.log('变更组权限:', {permissionId, groupType, granted});
    
    // 禁用复选框防止重复操作
    e.target.disabled = true;
    
    const formData = new FormData();
    formData.append('groupId', groupId);
    formData.append('permissionId', permissionId);
    formData.append('granted', granted);
    
    fetch('PermissionManagementServlet?action=updateGroupPermissions', {
        method: 'POST',
        body: formData
    })
    .then(response => {
        if (!response.ok) {
            throw new Error('HTTP ' + response.status + ': ' + response.statusText);
        }
        return response.json();
    })
    .then(data => {
        e.target.disabled = false;
        
        if (data.success) {
            // 更新状态显示
            const statusSpan = e.target.nextElementSibling;
            statusSpan.className = 'permission-status ' + (granted ? 'granted' : 'denied');
            statusSpan.textContent = granted ? '已授权' : '未授权';
            
            // 更新统计
            const currentStats = getCurrentPermissionStats(groupType);
            updatePermissionStats(groupType, currentStats.total, currentStats.granted + (granted ? 1 : -1));
            
            showMessage('权限更新成功', 'success');
        } else {
            // 恢复复选框状态
            e.target.checked = !granted;
            throw new Error(data.message || '更新权限失败');
        }
    })
    .catch(error => {
        e.target.disabled = false;
        e.target.checked = !granted;
        console.error('更新权限失败:', error);
        showMessage('更新权限失败: ' + error.message, 'error');
    });
}

// 获取当前权限统计
function getCurrentPermissionStats(groupType) {
    const container = document.getElementById(groupType + 'GroupPermissions');
    const checkboxes = container.querySelectorAll('.permission-checkbox');
    const checkedBoxes = container.querySelectorAll('.permission-checkbox:checked');
    
    return {
        total: checkboxes.length,
        granted: checkedBoxes.length
    };
}

//1. 修复 loadUsersByType 函数 - 专门为用户权限管理设计
function loadUsersByType() {
    const userTypeRadio = document.querySelector('input[name="userType"]:checked');
    const userType = userTypeRadio ? userTypeRadio.value : null;
    if (!userType) return;
    
    console.log('加载用户类型:', userType);
    
    // 显示加载状态
    const container = document.getElementById('permissionUserList');
    if (!container) {
        console.error('找不到用户列表容器 #permissionUserList');
        return;
    }
    
    container.innerHTML = '<div class="loading-placeholder">' +
                         '<i class="fas fa-spinner fa-spin"></i>' +
                         '<span>加载用户中...</span>' +
                         '</div>';
    
    fetch('PermissionManagementServlet?action=getUsersByGroup')
        .then(response => {
            if (!response.ok) {
                throw new Error('HTTP ' + response.status + ': ' + response.statusText);
            }
            return response.json();
        })
        .then(data => {
            console.log('用户数据响应:', data);
            if (data.success) {
                const users = userType === 'admin' ? (data.adminUsers || []) : (data.normalUsers || []);
                console.log(userType + ' 用户数量:', users.length);
                
                // 使用专门的渲染函数渲染到权限管理的用户列表容器
                renderPermissionUserList(users, container);
                
                // 清除当前选择的用户
                if (typeof permissionData !== 'undefined') {
                    permissionData.currentSelectedUser = null;
                }
                
                // 重置权限设置区域
                resetPermissionSettingsArea();
                
            } else {
                throw new Error(data.message || '获取用户列表失败');
            }
        })
        .catch(error => {
            console.error('加载用户列表失败:', error);
            container.innerHTML = '<div class="error-state">' +
                                '<i class="fas fa-exclamation-triangle"></i>' +
                                '<p>加载失败: ' + error.message + '</p>' +
                                '<button class="btn btn-secondary btn-sm" onclick="loadUsersByType()">' +
                                '<i class="fas fa-redo"></i> 重试' +
                                '</button>' +
                                '</div>';
            showMessage('加载用户失败: ' + error.message, 'error');
        });
}

//2. 新增专门的权限管理用户列表渲染函数
function renderPermissionUserList(users, container) {
    console.log('渲染权限管理用户列表，用户数量:', users.length);
    
    if (!container) {
        console.error('渲染容器未找到');
        return;
    }
    
    // 清空容器
    container.innerHTML = '';
    
    if (!users || users.length === 0) {
        container.innerHTML = '<div class="empty-hint">' +
                             '<i class="fas fa-users"></i>' +
                             '<p>没有找到用户</p>' +
                             '</div>';
        return;
    }
    
    // 渲染每个用户
    for (var i = 0; i < users.length; i++) {
        var user = users[i];
        
        try {
            console.log('处理用户 ' + (i + 1) + ':', user);
            
            // 提取用户数据 - 使用安全的方式，避免EL表达式
            var userId = user.userId || user.id || 'unknown';
            var username = user.username || user.name || 'unknown';
            var email = user.email || '';
            var userType = user.userType || user.type || 'USER';
            var status = user.status || 'ACTIVE';
            
            // 创建用户项DOM元素 - 使用字符串拼接而非模板字符串
            var userItem = document.createElement('div');
            userItem.className = 'user-item';
            userItem.setAttribute('data-user-id', userId);
            userItem.setAttribute('data-user-type', userType);
            userItem.setAttribute('data-username', username);
            
            // 构建HTML内容 - 使用字符串拼接
            var userHtml = '<i class="fas fa-user"></i>' +
                          '<div class="user-info">' +
                          '<div class="username">' + escapeHtml(username) + '</div>' +
                          '<div class="email">' + escapeHtml(email || '无邮箱') + '</div>' +
                          '</div>';
            
            userItem.innerHTML = userHtml;
            
            // 添加点击事件 - 选择用户（使用闭包避免循环变量问题）
            (function(currentUserId, currentUsername) {
                userItem.addEventListener('click', function() {
                    // 移除其他用户的选中状态
                    var allUserItems = container.querySelectorAll('.user-item');
                    for (var j = 0; j < allUserItems.length; j++) {
                        allUserItems[j].classList.remove('active');
                    }
                    
                    // 选中当前用户
                    userItem.classList.add('active');
                    
                    // 加载该用户的权限设置
                    selectUserForPermissionSetting(currentUserId, currentUsername);
                });
            })(userId, username);
            
            // 添加到容器
            container.appendChild(userItem);
            
        } catch (error) {
            console.error('处理用户项出错:', error, user);
        }
    }
    
    console.log('权限管理用户列表渲染完成');
}

//3. 选择用户进行权限设置的函数
function selectUserForPermissionSetting(userId, username) {
    console.log('选择用户设置权限:', 'userId=' + userId, 'username=' + username);
    
    // 保存当前选择的用户
    if (typeof permissionData !== 'undefined') {
        permissionData.currentSelectedUser = userId;
    }
    
    // 更新标题显示
    var selectedUserNameEl = document.getElementById('selectedUserName');
    if (selectedUserNameEl) {
        selectedUserNameEl.textContent = '（' + username + '）';
    }
    
    // 显示权限设置区域
    showPermissionSettingsArea();
    
    // 加载用户权限
    loadUserPermissionSettings(userId);
}

//6. 加载用户权限设置
function loadUserPermissionSettings(userId) {
    console.log('加载用户权限设置，userId=' + userId);
    
    var settingsContainer = document.getElementById('userPermissionSettings');
    if (!settingsContainer) {
        console.error('找不到权限设置容器');
        return;
    }
    
    settingsContainer.innerHTML = '<div class="loading-placeholder">' +
                                 '<i class="fas fa-spinner fa-spin"></i>' +
                                 '<span>加载用户权限中...</span>' +
                                 '</div>';
    
    var url = 'PermissionManagementServlet?action=getUserPermissions&userId=' + userId;
    
    fetch(url)
        .then(response => {
            if (!response.ok) {
                throw new Error('HTTP ' + response.status + ': ' + response.statusText);
            }
            return response.json();
        })
        .then(data => {
            console.log('用户权限数据:', data);
            if (data.success) {
                renderUserPermissionSettings(data.allPermissions || [], data.userPermissions || {}, data.groupPermissionIds || []);
                updatePermissionSummaryDisplay(data.userPermissions || {}, data.groupPermissionIds || []);
            } else {
                throw new Error(data.message || '获取用户权限失败');
            }
        })
        .catch(error => {
            console.error('加载用户权限失败:', error);
            settingsContainer.innerHTML = '<div class="error-state">' +
                                         '<i class="fas fa-exclamation-triangle"></i>' +
                                         '<p>加载失败: ' + error.message + '</p>' +
                                         '</div>';
            showMessage('加载用户权限失败: ' + error.message, 'error');
        });
}

//7. 渲染用户权限设置界面
function renderUserPermissionSettings(permissions, userPerms, groupPerms) {
    var container = document.getElementById('userPermissionSettings');
    
    if (!permissions || permissions.length === 0) {
        container.innerHTML = '<div class="empty-hint">暂无权限数据</div>';
        return;
    }
    
    var html = '';
    for (var i = 0; i < permissions.length; i++) {
        var permission = permissions[i];
        var permissionId = permission.permissionId;
        var userPerm = userPerms[permissionId];
        var hasGroupPerm = groupPerms.indexOf(permissionId) !== -1;
        var delay = (i * 0.05) + 's';
        
        var status, statusClass;
        if (userPerm !== undefined) {
            status = userPerm ? '个人授权' : '个人拒绝';
            statusClass = userPerm ? 'granted' : 'denied';
        } else {
            status = hasGroupPerm ? '组授权' : '组拒绝';
            statusClass = hasGroupPerm ? 'granted' : 'denied';
        }
        
        // 构建权限项HTML - 使用字符串拼接
        html += '<div class="permission-item" style="animation-delay: ' + delay + '">' +
                '<span class="permission-name">' + (permission.permissionDescription || permission.permissionName) + '</span>' +
                '<div class="permission-toggle">' +
                '<label class="radio-option">' +
                '<input type="radio" name="perm_' + permissionId + '" value="true" ' +
                (userPerm === true ? 'checked' : '') + '>' +
                '<span>允许</span>' +
                '</label>' +
                '<label class="radio-option">' +
                '<input type="radio" name="perm_' + permissionId + '" value="false" ' +
                (userPerm === false ? 'checked' : '') + '>' +
                '<span>拒绝</span>' +
                '</label>' +
                '<label class="radio-option">' +
                '<input type="radio" name="perm_' + permissionId + '" value="default" ' +
                (userPerm === undefined ? 'checked' : '') + '>' +
                '<span>默认</span>' +
                '</label>' +
                '<span class="permission-status ' + statusClass + '">' + status + '</span>' +
                '</div>' +
                '</div>';
    }
    
    container.innerHTML = html;
    
    // 绑定事件监听器到新生成的单选按钮
    var radioButtons = container.querySelectorAll('input[type="radio"]');
    for (var j = 0; j < radioButtons.length; j++) {
        var radio = radioButtons[j];
        
        // 使用闭包避免循环变量问题
        (function(currentRadio) {
            currentRadio.addEventListener('change', function() {
                if (this.checked) {
                    var permissionId = this.name.replace('perm_', '');
                    var value = this.value;
                    
                    console.log('权限变更:', 'permissionId=' + permissionId, 'value=' + value);
                    
                    // 调用权限更新函数
                    if (value === 'default') {
                        updateUserPermissionSetting(permissionId, null);
                    } else {
                        updateUserPermissionSetting(permissionId, value === 'true');
                    }
                }
            });
        })(radio);
    }
    
    console.log('权限设置界面渲染完成，单选按钮数量:', radioButtons.length);
}

//9. 更新用户权限设置
function updateUserPermissionSetting(permissionId, granted) {
    if (typeof permissionData === 'undefined' || !permissionData.currentSelectedUser) {
        showMessage('请先选择用户', 'error');
        return;
    }
    
    console.log('更新用户权限设置:', 'userId=' + permissionData.currentSelectedUser, 'permissionId=' + permissionId, 'granted=' + granted);
    
    // 禁用相关控件防止重复操作
    var statusElements = document.querySelectorAll('input[name="perm_' + permissionId + '"]');
    for (var i = 0; i < statusElements.length; i++) {
        statusElements[i].disabled = true;
    }
    
    var actionUrl, formData = new FormData();
    formData.append('userId', permissionData.currentSelectedUser);
    formData.append('permissionId', permissionId);
    
    if (granted === null) {
        // 删除个人权限设置，使用默认（组权限）
        actionUrl = 'PermissionManagementServlet?action=removeUserPermission';
    } else {
        // 设置个人权限
        actionUrl = 'PermissionManagementServlet?action=setUserPermission';
        formData.append('granted', granted);
    }
    
    fetch(actionUrl, {
        method: 'POST',
        body: formData
    })
    .then(response => {
        if (!response.ok) {
            throw new Error('HTTP ' + response.status + ': ' + response.statusText);
        }
        return response.json();
    })
    .then(data => {
        // 恢复控件状态
        for (var i = 0; i < statusElements.length; i++) {
            statusElements[i].disabled = false;
        }
        
        if (data.success) {
            showMessage('权限设置成功', 'success');
            // 重新加载用户权限以更新显示
            loadUserPermissionSettings(permissionData.currentSelectedUser);
        } else {
            throw new Error(data.message || '权限设置失败');
        }
    })
    .catch(error => {
        // 恢复控件状态
        for (var i = 0; i < statusElements.length; i++) {
            statusElements[i].disabled = false;
        }
        console.error('权限设置失败:', error);
        showMessage('权限设置失败: ' + error.message, 'error');
        
        // 恢复之前的选择状态
        loadUserPermissionSettings(permissionData.currentSelectedUser);
    });
}

// 10. 安全的HTML转义函数
function escapeHtml(unsafe) {
    if (unsafe == null || unsafe === undefined) {
        return '';
    }
    return String(unsafe)
         .replace(/&/g, "&amp;")
         .replace(/</g, "&lt;")
         .replace(/>/g, "&gt;")
         .replace(/"/g, "&quot;")
         .replace(/'/g, "&#039;");
}

// 11. 初始化用户类型选择器
function initUserTypeSelector() {
    console.log('初始化用户类型选择器');
    
    var userTypeRadios = document.querySelectorAll('input[name="userType"]');
    for (var i = 0; i < userTypeRadios.length; i++) {
        var radio = userTypeRadios[i];
        
        // 使用闭包避免循环变量问题
        (function(currentRadio) {
            currentRadio.addEventListener('change', function(e) {
                var selectedType = e.target.value;
                console.log('用户类型已切换到:', selectedType);
                
                // 清除之前选中的用户
                resetPermissionSettingsArea();
                
                // 加载新类型的用户
                loadUsersByType();
            });
        })(radio);
    }
    
    // 默认加载管理员用户
    loadUsersByType();
}

console.log('修复后的权限管理用户渲染函数已加载');

//8. 更新权限摘要显示
function updatePermissionSummaryDisplay(userPermissions, groupPermissions) {
    var personalCount = Object.keys(userPermissions).length;
    var groupCount = groupPermissions.length;
    
    var personalCountEl = document.getElementById('personalCount');
    var groupPermCountEl = document.getElementById('groupPermCount');
    
    if (personalCountEl) personalCountEl.textContent = personalCount;
    if (groupPermCountEl) groupPermCountEl.textContent = groupCount;
}



//4. 显示权限设置区域
function showPermissionSettingsArea() {
    var settingsPanel = document.getElementById('userPermissionSettings');
    var actionsPanel = document.getElementById('permissionActions');
    var summaryPanel = document.getElementById('permissionSummary');
    
    if (settingsPanel) {
        settingsPanel.innerHTML = '<div class="loading-placeholder">' +
                                 '<i class="fas fa-spinner fa-spin"></i>' +
                                 '<span>加载权限中...</span>' +
                                 '</div>';
    }
    
    if (actionsPanel) {
        actionsPanel.style.display = 'flex';
    }
    
    if (summaryPanel) {
        summaryPanel.style.display = 'flex';
    }
}

// 5. 重置权限设置区域
function resetPermissionSettingsArea() {
    var settingsPanel = document.getElementById('userPermissionSettings');
    var actionsPanel = document.getElementById('permissionActions');
    var summaryPanel = document.getElementById('permissionSummary');
    var selectedUserName = document.getElementById('selectedUserName');
    
    if (settingsPanel) {
        settingsPanel.innerHTML = '<div class="no-user-selected">' +
                                 '<i class="fas fa-hand-point-left"></i>' +
                                 '<p>请从左侧选择要设置权限的用户</p>' +
                                 '<small>选择用户后可以为其设置个性化权限</small>' +
                                 '</div>';
    }
    
    if (actionsPanel) {
        actionsPanel.style.display = 'none';
    }
    
    if (summaryPanel) {
        summaryPanel.style.display = 'none';
    }
    
    if (selectedUserName) {
        selectedUserName.textContent = '（请选择用户）';
    }
}

// 渲染用户列表
//同时需要更新 renderUserList 函数，移除内联的 onclick 并在末尾调用 bindUserActionEvents
//渲染用户列表的函数
function renderUserList(users) {
    const adminList = document.getElementById('adminUserList');
    const userList = document.getElementById('normalUserList');
    const accountsTable = document.getElementById('accountsTableBody');
    
    // 检查DOM元素是否存在
    if (!adminList || !userList || !accountsTable) {
        console.error('❌ 关键DOM元素未找到:', {
            adminList: !!adminList,
            userList: !!userList,
            accountsTable: !!accountsTable
        });
        throw new Error('页面元素加载异常，请刷新页面');
    }
    
    // 清空现有内容
    adminList.innerHTML = '';
    userList.innerHTML = '';
    accountsTable.innerHTML = '';

    users.forEach((user, index) => {
        try {
            console.log(`处理用户 ${index + 1}:`, user);
            
            // 🔧 兼容不同的字段名格式
            const userId = user.userId || user.user_id || user.id;
            const username = user.username || user.userName || user.user_name;
            const userType = user.userType || user.user_type || user.type;
            const status = user.status || user.userStatus || user.user_status || 'ACTIVE';
            const email = user.email || user.userEmail || user.user_email;
            const createdAt = user.createdAt || user.created_at || user.createTime;
            
            // 验证必需字段
            if (!userId || !username) {
                console.warn('⚠️ 用户数据不完整:', user);
                return; // 跳过这个用户
            }
            
            // 添加到用户组管理列表
            const userItem = document.createElement('div');
            userItem.className = 'user-item';
            userItem.innerHTML = `
                <i class="fas fa-user"></i>
                <div class="user-info">
                    <div class="username">${username}</div>
                    <div class="email">${email || '无邮箱'}</div>
                </div>
            `;
            userItem.setAttribute('data-user-id', userId);
            userItem.setAttribute('data-username', username);
            userItem.setAttribute('data-user-type', userType);
            
            // 根据用户类型分组
            if (userType === 'ADMIN' || userType === 'admin') {
                adminList.appendChild(userItem);
            } else {
                userList.appendChild(userItem);
            }
            
            // 添加到账户列表表格
            const row = document.createElement('tr');
            row.innerHTML = `
                <td>${username}</td>
                <td>${userType === 'ADMIN' || userType === 'admin' ? '管理员' : '普通用户'}</td>
                <td><span class="user-status ${status.toLowerCase()}" data-id="${username}">${status}</span></td>
                <td>${formatBackendDate(createdAt)}</td>
                <td>
                    <button class="btn-link reset-password" data-id="${username}" title="重置密码">
                        <i class="fas fa-key"></i>
                    </button>
                    <button class="btn-link lock-unlock-btn" data-id="${username}" data-status="${status}" title="${status === 'ACTIVE' ? '锁定' : '解锁'}">
                        <i class="fas ${status === 'ACTIVE' ? 'fa-lock' : 'fa-unlock'}"></i>
                    </button>
                    <button class="btn-link delete-user" data-id="${userId}" title="删除">
                        <i class="fas fa-trash"></i>
                    </button>
                </td>
            `;
            
            accountsTable.appendChild(row);
            
        } catch (userError) {
            console.error('❌ 处理用户出错:', userError, user);
        }
    });
    
    // 重新绑定事件监听器
    bindUserActionEvents();
    
    // 更新用户计数
    updateUserCounts();
}


// 过滤用户
function filterUsers() {
    const searchInput = document.getElementById('userSearchInput');
    const searchTerm = searchInput ? searchInput.value.toLowerCase() : '';
    const userItems = document.querySelectorAll('#permissionUserList .user-item');
    
    userItems.forEach(item => {
        const usernameEl = item.querySelector('.username');
        const emailEl = item.querySelector('.email');
        const username = usernameEl ? usernameEl.textContent.toLowerCase() : '';
        const email = emailEl ? emailEl.textContent.toLowerCase() : '';
        
        if (username.indexOf(searchTerm) !== -1 || email.indexOf(searchTerm) !== -1) {
            item.style.display = '';
            item.style.animation = 'fadeInScale 0.3s ease';
        } else {
            item.style.display = 'none';
        }
    });
}

// 选择用户进行权限设置
function selectUserForPermission(userId, username) {
    console.log('选择用户设置权限:', {userId, username});
    
    permissionData.currentSelectedUser = userId;
    
    // 更新选中状态
    document.querySelectorAll('#permissionUserList .user-item').forEach(item => {
        item.classList.remove('active');
    });
    event.target.closest('.user-item').classList.add('active');
    
    // 更新标题
    const selectedUserNameEl = document.getElementById('selectedUserName');
    if (selectedUserNameEl) {
        selectedUserNameEl.textContent = '（' + username + '）';
    }
    
    // 显示操作按钮和摘要
    const permissionActions = document.getElementById('permissionActions');
    const permissionSummary = document.getElementById('permissionSummary');
    
    if (permissionActions) {
        permissionActions.style.display = 'flex';
    }
    if (permissionSummary) {
        permissionSummary.style.display = 'flex';
    }
    
    // 加载用户权限
    loadUserPermissions(userId);
}

// 加载用户权限
function loadUserPermissions(userId) {
    const settingsContainer = document.getElementById('userPermissionSettings');
    settingsContainer.innerHTML = '<div class="loading-placeholder"><i class="fas fa-spinner fa-spin"></i><span>加载用户权限中...</span></div>';
    
    fetch('PermissionManagementServlet?action=getUserPermissions&userId=' + userId)
        .then(response => {
            if (!response.ok) {
                throw new Error('HTTP ' + response.status + ': ' + response.statusText);
            }
            return response.json();
        })
        .then(data => {
            console.log('用户权限数据:', data);
            if (data.success) {
                renderUserPermissions(data.allPermissions, data.userPermissions, data.groupPermissionIds);
                updatePermissionSummary(data.userPermissions, data.groupPermissionIds);
            } else {
                throw new Error(data.message || '获取用户权限失败');
            }
        })
        .catch(error => {
            console.error('加载用户权限失败:', error);
            settingsContainer.innerHTML = '<div class="error-state"><i class="fas fa-exclamation-triangle"></i><p>加载失败: ' + error.message + '</p></div>';
            showMessage('加载用户权限失败: ' + error.message, 'error');
        });
}

// 渲染用户权限设置
function renderUserPermissions(permissions, userPerms, groupPerms) {
    const container = document.getElementById('userPermissionSettings');
    
    if (!permissions || permissions.length === 0) {
        container.innerHTML = '<div class="empty-hint">暂无权限数据</div>';
        return;
    }
    
    var html = '';
    for (var i = 0; i < permissions.length; i++) {
        var permission = permissions[i];
        var userPerm = userPerms[permission.permissionId];
        var hasGroupPerm = groupPerms.indexOf(permission.permissionId) !== -1;
        var delay = (i * 0.05) + 's';
        
        var status, statusClass;
        if (userPerm !== undefined) {
            status = userPerm ? '个人授权' : '个人拒绝';
            statusClass = userPerm ? 'granted' : 'denied';
        } else {
            status = hasGroupPerm ? '组授权' : '组拒绝';
            statusClass = hasGroupPerm ? 'granted' : 'denied';
        }
        
        html += '<div class="permission-item" style="animation-delay: ' + delay + '">' +
                '<span class="permission-name">' + (permission.permissionDescription || permission.permissionName) + '</span>' +
                '<div class="permission-toggle">' +
                '<label class="radio-option">' +
                '<input type="radio" name="perm_' + permission.permissionId + '" value="true" ' +
                (userPerm === true ? 'checked' : '') + '>' +
                '<span>允许</span>' +
                '</label>' +
                '<label class="radio-option">' +
                '<input type="radio" name="perm_' + permission.permissionId + '" value="false" ' +
                (userPerm === false ? 'checked' : '') + '>' +
                '<span>拒绝</span>' +
                '</label>' +
                '<label class="radio-option">' +
                '<input type="radio" name="perm_' + permission.permissionId + '" value="default" ' +
                (userPerm === undefined ? 'checked' : '') + '>' +
                '<span>默认</span>' +
                '</label>' +
                '<span class="permission-status ' + statusClass + '">' + status + '</span>' +
                '</div>' +
                '</div>';
    }
    
    container.innerHTML = html;
    
    // 修复：绑定事件监听器到新生成的单选按钮
    container.querySelectorAll('input[type="radio"]').forEach(radio => {
        radio.addEventListener('change', function() {
            if (this.checked) {
                const permissionId = this.name.replace('perm_', '');
                const value = this.value;
                
                console.log('权限变更:', {
                    permissionId: permissionId,
                    value: value,
                    userId: permissionData.currentSelectedUser
                });
                
                // 调用权限更新函数
                if (value === 'default') {
                    handleUserPermissionChange(permissionId, null);
                } else {
                    handleUserPermissionChange(permissionId, value === 'true');
                }
            }
        });
    });
    
    console.log('权限设置界面渲染完成，单选按钮数量:', container.querySelectorAll('input[type="radio"]').length);
}

// 更新权限摘要
function updatePermissionSummary(userPermissions, groupPermissions) {
    const personalCount = Object.keys(userPermissions).length;
    const groupCount = groupPermissions.length;
    
    const personalCountEl = document.getElementById('personalCount');
    const groupPermCountEl = document.getElementById('groupPermCount');
    
    if (personalCountEl) personalCountEl.textContent = personalCount;
    if (groupPermCountEl) groupPermCountEl.textContent = groupCount;
}

// 重置用户权限
function resetUserPermissions() {
    if (!permissionData.currentSelectedUser) return;
    
    if (confirm('确定要将该用户的权限重置为默认值吗？')) {
        const formData = new FormData();
        formData.append('userId', permissionData.currentSelectedUser);
        
        showLoader();
        
        fetch('PermissionManagementServlet?action=resetUserPermissions', {
            method: 'POST',
            body: formData
        })
        .then(response => {
            if (!response.ok) {
                throw new Error('HTTP ' + response.status + ': ' + response.statusText);
            }
            return response.json();
        })
        .then(data => {
            hideLoader();
            if (data.success) {
                showMessage(data.message, 'success');
                loadUserPermissions(permissionData.currentSelectedUser);
            } else {
                throw new Error(data.message || '重置权限失败');
            }
        })
        .catch(error => {
            hideLoader();
            console.error('重置权限失败:', error);
            showMessage('重置权限失败: ' + error.message, 'error');
        });
    }
}

// 预览用户权限效果
function previewUserPermissions() {
    const permissions = document.querySelectorAll('#userPermissionSettings input[type="radio"]:checked');
    const preview = [];
    
    permissions.forEach(radio => {
        const permissionId = radio.name.replace('perm_', '');
        const value = radio.value;
        const permissionItem = radio.closest('.permission-item');
        const permissionNameEl = permissionItem ? permissionItem.querySelector('.permission-name') : null;
        const permissionName = permissionNameEl ? permissionNameEl.textContent : '';
        
        if (value !== 'default') {
            preview.push({
                name: permissionName,
                status: value === 'true' ? '允许' : '拒绝'
            });
        }
    });
    
    if (preview.length === 0) {
        showMessage('当前用户使用组默认权限', 'info');
        return;
    }
    
    var previewText = '个人权限设置预览：\n\n';
    for (var i = 0; i < preview.length; i++) {
        var p = preview[i];
        previewText += '• ' + p.name + ': ' + p.status + '\n';
    }
    
    alert(previewText);
}

// 保存用户权限
function saveUserPermissions() {
    if (!permissionData.currentSelectedUser) return;
    
    const permissions = document.querySelectorAll('#userPermissionSettings input[type="radio"]:checked');
    const updates = [];
    
    permissions.forEach(radio => {
        const permissionId = radio.name.replace('perm_', '');
        const value = radio.value;
        
        if (value !== 'default') {
            updates.push(permissionId + ':' + (value === 'true'));
        }
    });
    
    if (updates.length === 0) {
        showMessage('没有需要保存的权限更改', 'info');
        return;
    }
    
    showLoader();
    
    // 发送更新请求
    const promises = updates.map(permissionDataStr => {
        const formData = new FormData();
        formData.append('userId', permissionData.currentSelectedUser);
        formData.append('permissionData', permissionDataStr);
        
        return fetch('PermissionManagementServlet?action=updateUserPermissions', {
            method: 'POST',
            body: formData
        });
    });
    
    Promise.all(promises)
        .then(responses => {
            const jsonPromises = responses.map(r => {
                if (!r.ok) {
                    throw new Error('HTTP ' + r.status + ': ' + r.statusText);
                }
                return r.json();
            });
            return Promise.all(jsonPromises);
        })
        .then(results => {
            hideLoader();
            const allSuccess = results.every(r => r.success);
            if (allSuccess) {
                showMessage('用户权限保存成功', 'success');
                loadUserPermissions(permissionData.currentSelectedUser);
            } else {
                const errors = results.filter(r => !r.success).map(r => r.message);
                throw new Error('部分权限保存失败: ' + errors.join(', '));
            }
        })
        .catch(error => {
            hideLoader();
            console.error('保存权限失败:', error);
            showMessage('保存权限失败: ' + error.message, 'error');
        });
}